package com.leyou.upload.service;

import com.github.tobato.fastdfs.domain.MateData;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.leyou.upload.controller.UploadController;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

/**
 * @author CHERRY
 * @date 2018-09-03-0:21
 */
@Service
public class UploadService {

    private static final Logger LOGGER = LoggerFactory.getLogger(UploadController.class);

    /**
     * 支持的文件类型
     */
    private static final List<String> SUFFIXES = Arrays.asList("image/jpeg", "image/png", "application/x-jpg");
    public static final Set<MateData> SET = null;
    @Autowired
    private FastFileStorageClient storageClient;

    public String uploadFile(MultipartFile file) {
        try {
            //图片信息校验
            //校验图片类型
            String type = file.getContentType();
            if (!SUFFIXES.contains(type)) {
                //{} 占位符
                LOGGER.info("文件类型不匹配{}" + type);
                return null;
            }
            //校验图片内容
            BufferedImage image = ImageIO.read(file.getInputStream());
            if (image == null) {
                //图片上传错误
                LOGGER.info("上传失败，文件内容不符合要求");
                return null;
            }
            //保存图片
            /*file.transferTo(new File("C:\\Users\\CHERRY\\Desktop\\" + file.getOriginalFilename()));
            String url = "http://image.leyou.com/" + file.getOriginalFilename();*/
            //文件后缀名
            String extension = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
            StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), extension, null);
            return "http://image.leyou.com/" + storePath.getFullPath();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
